from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver import ChromeOptions

# 无头浏览器设置
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
# 规避检查
options = ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])

bro = webdriver.Chrome(executable_path="./chromedriver.exe", chrome_options=chrome_options, options=options)

# ============================= #
#           爬取车销量
# ============================= #

with open("data/series.txt", "r", encoding="utf-8") as lines:
    for line in lines:
        # print(line.split(",")[0])

        bro.get("https://price.pcauto.com.cn/salescar/" + line.split(",")[0] + "/")

        try:
            table = bro.find_element_by_tag_name("tbody")
            content = table.find_element_by_class_name("tr-ser")
            item = line.split(",")[0] + ","
            for td in content.find_elements_by_tag_name("td"):
                item = item + td.text + ","
            print(item)
            with open(
                    "data/sale_new.csv",
                    "a", encoding="utf-8") as file:
                file.write(item[:-1] + "\n")

        except:
            pass
